import Vue from "vue";
import router from "./router";
import store from "./store";
//进度条
import NProgress from "nprogress";
import "nprogress/nprogress.css";
//其实就是把component引入这个功能
import { generateIndexRouter } from "@/utils/generateIndexRouter";

NProgress.configure({ showSpinner: false });

//即去的地方本身就是登录，就不用检查token
const whiteList = ["/user/login", "/user/forgetPassword"];

//其实直接输入要进去以后的网址，但是会被拦截，因为没有token,所以会跳转到login的地方，然后保留redirect成功后再跳转，否则进入首页
//GetPermissionList行动会用token去请求这个人的菜单有什么东西，也就是返回PermissionList，menuData也即是PermissionList，generateIndexRouter会把
//menuData的component变成真正的引入，然后addRoutes加在原本就有的route配置项里，生成路由就做完了
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (Vue.local.get("ACCESS_TOKEN")) {
    if (to.path === "/user/login") {
      next({ path: "/user/login" });
      NProgress.done();
    } else {
      if (store.getters.permissionList.length === 0) {
        store.dispatch("GetPermissionList").then((res) => {
          const menuData = res;
          if (menuData === null || menuData === "" || menuData === undefined) {
            return;
          }
          let constRoutes = [];
          constRoutes = generateIndexRouter(menuData);
          router.addRoutes(constRoutes);
          const redirect = decodeURIComponent(from.query.redirect || to.path);
          if (to.path === redirect) {
            next({ ...to, replace: true }); 
          } else {
            next({ path: redirect });
          }
        }).catch(()=>{
            store.dispatch('Logout').then(()=>{
                next({path:'/user/login',query:{redirect:to.fullPath}})
            })
        })
      }else{
          next()
      }
    }
  }else{
      
      if(whiteList.indexOf(to.path)!==-1){
          next()
          NProgress.done()
      }else{
          let path='/user/login'
          //这里保留要去的地方很妙
          next({ path: path, query: { redirect: to.fullPath } }) 
          NProgress.done() 
      }
  }
})

router.afterEach(()=>{
    NProgress.done()
})
